// subPages/health/recordSize/recordSize.js
import * as echarts from '../../../ec-canvas/echarts';
var util =  require('../../../utils/util.js');
var navListJson = require('../../../data/navListJson');
let LineChart = null
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    ec: {
      // lazyLoad: true // 延迟加载
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.type != 'undefined' && options.type != null){
        this.setData({
            typeNum: options.type
        })
    }
    if(options.weight != 'undefined' && options.weight != null){
        this.setData({
            weight: options.weight
        })
    }
    this.setDate()
  },

  //设置日期
  setDate:function(){
    var that = this
    let date = util.setTime10(new Date())
    let Y = date.split('-')
    that.setData({
      date: date,
      dateStart: Y[0]- 3,
      dateEnd: date,
      navList: navListJson.recordSizeNavList,
      thList: navListJson.recordSizeThList
    })
    that.getData(date)
  },

  bindDateChange: function(e) {
    var that = this
    that.setData({
      date: e.detail.value,
    })
    that.getData(that.data.date)
  },

  //获得数据
  getData:function(date){
    var that = this
    wx.request({
        url: app.globalData.apiUrl +'/get_weight',
        data: {
          userid: app.globalData.userId,
          time: date
        },
        method: 'get',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            that.processingData(res.data.data.list);
            var isEchart = that.processingEchartData(res.data.data.arr);
            if(isEchart){
              that.setData({
                isData: true,
                isEchart: isEchart,
                type: 'weight'
              })
              LineChart = null
              that.getLineGraphData(that.data.weightData,that.data.weightTime);  //创建图表
            }else{
              that.setData({
                isData: false,
                tipTxt: {
                  tipTxt: '暂无测量数据',
                  tipImg: '/resources/index/noData.png'
                }
              })
            }
          }else{
            util.showModal('提示','数据异常')
            return;
          }
        },
        fail: function (res) {
          console.log("失败",res);
        }
    })
  },

  //处理数据
  processingData:function(list){
    var that = this
    if(list.length != 0){
      for(var i in list){
        var date = list[i].createtime.substring(8,10)
        list[i].createtime = date + '日'
      }
      that.setData({
        isData2: true,
        historyList: list,
      })
    }else{
      that.setData({
        isData2: false,
        tipTxt2: {
          tipTxt2: '暂无测量数据',
          tipImg2: '/resources/index/noDataSmall.png'
        }
      })
    }
  },

  //处理图表数据
  processingEchartData:function(arr){
    var that = this
    if(arr.length != 0){
      //体重
      if(arr.weight){
        var weightData = [];
        var weightTime = []
        for(var i=0;i<arr.weight.length;i++)
        {
          weightData.push(arr.weight[i].weight)
          var time = util.setTime(arr.weight[i].createtime.substring(0,10))
          weightTime.push(time)
        }
        that.setData({
          isWeightData: true,
          weightData: weightData,
          weightTime: weightTime
        })
      }else{
        that.setData({
          isWeightData: false,
          weightData: weightData,
          weightTime: weightTime
        })
      }
      //BMI
      if(arr.bmi){
        var bmiData = [];
        var bmiTime = []
        for(var i=0;i<arr.bmi.length;i++)
        {
          bmiData.push(arr.bmi[i].bmi)
          var time = util.setTime(arr.bmi[i].createtime.substring(0,10))
          bmiTime.push(time)
        }
        that.setData({
          isBmiData: true,
          bmiData: bmiData,
          bmiTime: bmiTime
        })
      }else{
        that.setData({
          isBmiData: false,
          bmiData: bmiData,
          bmiTime: bmiTime
        })
      }
      //腰臀比
      if(arr.core){
        var coreData = [];
        var coreTime = []
        for(var i=0;i<arr.core.length;i++)
        {
          coreData.push(arr.core[i].core)
          var time = util.setTime(arr.core[i].createtime.substring(0,10))
          coreTime.push(time)
        }
        that.setData({
          isCoreData: true,
          coreData: coreData,
          coreTime: coreTime
        })
      }else{
        that.setData({
          isCoreData: false,
          coreData: [],
          coreTime: []
        })
      }
      return true
    }else{
      return false
    }
  },

  //线图表
  getLineGraphData:function(data,time){
    if(data == null || time == null) return;
    var that = this
    if (!LineChart){
      that.init_LineEcharts(data,time); //初始化图表
    }else{
      that.setLineOption(data,time); //更新数据
    }
  },

  //初始化图表
  init_LineEcharts: function (data,time) {
    var that = this
    that.linechartsComponnet = that.selectComponent('#mychartLine');
    that.linechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      LineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      LineChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setLineOption(data,time);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return LineChart;
    });
  },

  setLineOption: function (data,time) {
    LineChart.clear();  // 清除
    LineChart.setOption(this.getLineOption(data,time));  //获取新数据
  },

  //设置折线图表
  getLineOption: function (data,time) {
    var that = this
    // var end = (8 / data.length) * 100
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: '',
        subtext: ''
      },
      grid:{ 
        borderWidth:0,
        x:10,
        y:30,
        x2:10,
        y2:0,
        containLabel: true
      },
      xAxis: {
        type: 'category',
        show:true,
        boundaryGap:true,
        data : time,
        axisLine:{
          show:true,
          lineStyle:{
            color: 'white',
            width: 1,
          }
        },
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          color: 'white',
          interval: 0,
          formatter: '{value}',
          formatter:function(value){
            return util.setTime13(value) + '日'
          }
        },
      },
      yAxis: {
        type: 'value',
        boundaryGap:false,
        show:true,
        scale: false,
        splitNumber:2,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine:{
          show:true,
          lineStyle:{
            color: 'rgba(255,255,255,0.3)',
          }
        },
        axisLabel:{
          show: true,
          inside: true,
          verticalAlign: 'bottom',
          margin: 0,
          color: '#76ebdc',
          formatter:function(value,index){
            if(index == 0){
              return value
            }
            switch (that.data.type) {
              case 'weight':
                return value + 'kg'
              case 'BMI':
                return value
              case 'WHR':
                return value + '%'
            }
          }
        },
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: util.dataZoom(data),
          end: 100,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'',
        type:'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#fff',
          }
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              return params.data;
            }
          },
          itemStyle:{
            borderWidth: 12,
            borderType:'solid',
            borderColor: 'rgba(246,246,246,0.5)'
          }
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
                offset: 0, color: 'rgba(255,255,255,0)' // 0% 处的颜色
            }, {
                offset: 1, color: 'rgba(255,255,255,0.2)' // 100% 处的颜色
            }],
            globalCoord: false // 缺省为 false
          }
        },
        data:data
      }]
    };
    LineChart.hideLoading()
    return option;
  },

  //选择导航栏
  switchNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;
    if (that.data.currentTab == cur) {
      return false;
    } else {
      that.setData({
          currentTab: cur
      })
      if(that.data.isEchart){
        that.setEchartsData(cur)
      }
    }
  },

  //给图表赋值
  setEchartsData:function(cur){
    var that = this
    switch (cur) {
      case 0:
        //体重
        if(that.data.isWeightData){
          that.setData({
            isData: true,
            type: 'weight'
          })
          LineChart = null
          that.getLineGraphData(that.data.weightData,that.data.weightTime)
        }else{
          that.setData({
            isData: false,
            tipTxt: {
              tipTxt: '暂无测量数据',
              tipImg: '/resources/index/noData.png'
            }
          })
        }
        break;
      case 1:
        //bmi
        if(that.data.isBmiData){
          that.setData({
            isData: true,
            type: 'BMI'
          })
          LineChart = null
          that.getLineGraphData(that.data.bmiData,that.data.bmiTime)
        }else{
          that.setData({
            isData: false,
            tipTxt: {
              tipTxt: '暂无测量数据',
              tipImg: '/resources/index/noData.png'
            }
          })
        }
        break;
      case 2:
        //腰臀比
        if(that.data.isCoreData){
          that.setData({
            isData: true,
            type: 'WHR'
          })
          LineChart = null
          that.getLineGraphData(that.data.coreData,that.data.coreTime)
        }else{
          that.setData({
            isData: false,
            tipTxt: {
              tipTxt: '暂无测量数据',
              tipImg: '/resources/index/noData.png'
            }
          })
        }
        break;
    }
  },

  //记录按钮
  recordBtn:function(){
    var that = this
    if(that.data.typeNum == '1'){
      wx.navigateTo({
        url: '/subPages/health/recordWeight/recordWeight?weight=' + that.data.weight
      })
    }else{
      //返回
      wx.navigateBack({
        delta:1
      })
    }
  },

  //测量分析
  analysis:function(e){
    // console.log(e)
    wx.navigateTo({
      url: '../analysis/analysis?id=' + e.currentTarget.dataset.id + '&yes=' + 1
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.date){
      this.getData(this.data.date)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    LineChart = null
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    LineChart = null
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN健康管理',
      path: 'pages/index/index',
      success: function(res) {
        // res.shareTickets
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})
